export default {
  inserted: function(el, binding) {
    const element = binding.value.el ? document.querySelector(binding.value.el) : document.documentElement
    el.onclick = function() {
      let total
      if (binding.value.id === 0) {
        total = 0
      } else {
        const ele = document.querySelector(`#anchor-${binding.value.id}`)
        total = ele.offsetTop
      }
      let distance = binding.value.el ? document.querySelector(binding.value.el).scrollTop : document.documentElement || document.body.scrollTop
      let step = total / 30
      if (total > distance) {
        (function smoothDown() {
          if (distance < total) {
            distance += step
            element.scrollTop = distance
            setTimeout(smoothDown, 5)
          } else {
            element.scrollTop = total
          }
        })()
      } else {
        const newTotal = distance - total
        step = newTotal / 20;
        (function smoothUp() {
          if (distance > total) {
            distance -= step
            element.scrollTop = distance
            setTimeout(smoothUp, 5)
          } else {
            element.scrollTop = total
          }
        })()
      }
    }
  }
}
